<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-section">
      <u-search
        v-model="searchText"
        placeholder="搜索书籍"
        :show-action="false"
        :clearabled="true"
        @search="onSearch"
        @custom="onSearch"
      ></u-search>
    </view>

    <!-- 书架内容 -->
    <view class="bookshelf">
      <view class="bookshelf-header">
        <text class="title">我的书架</text>
        <text class="count">({{ filteredBooks.length }})</text>
      </view>
      
      <!-- 书籍列表 -->
      <view v-if="filteredBooks.length > 0" class="books-grid">
        <view 
          v-for="(book, index) in filteredBooks" 
          :key="index"
          class="book-item"
          @click="openBook(book)"
        >
          <view class="book-cover">
            <u-image
              :src="book.cover || '/static/default-cover.png'"
              width="80px"
              height="120px"
              :fade="true"
              mode="aspectFill"
            ></u-image>
          </view>
          <view class="book-info">
            <text class="book-title">{{ book.title }}</text>
            <text class="book-author">{{ book.author || '未知作者' }}</text>
            <text class="book-progress">已读 {{ book.progress || 0 }}%</text>
          </view>
        </view>
      </view>
      
      <!-- 空书架提示 -->
      <view v-else class="empty-bookshelf">
        <u-empty
          text="书架空空如也"
          mode="list"
          icon="https://cdn.uviewui.com/uview/empty/list.png"
        >
          <u-button 
            type="primary" 
            size="medium"
            @click="goToImport"
          >
            去导入书籍
          </u-button>
        </u-empty>
      </view>
    </view>

    <!-- 自定义底部导航（list模式） -->
    <u-tabbar v-model="current" :list="tabBarList" :fixed="true" :placeholder="true" @change="onTabChange" />
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';

// 隐藏原生tabbar
onMounted(() => {
  uni.hideTabBar({ animation: false });
});
// 保守处理：页面展示时再隐藏一次
onShow(() => {
  uni.hideTabBar({ animation: false });
  current.value = 0;
});

// 自定义tabbar配置
const tabBarList = ref([
  { iconPath: 'home', selectedIconPath: 'home-fill', text: '首页' },
  { iconPath: 'plus', selectedIconPath: 'plus', text: '导入', midButton: false },
  { iconPath: 'account', selectedIconPath: 'account-fill', text: '我的' }
]);

// 响应式数据
const searchText = ref('');
const books = ref([]);
const current = ref(0);

// 计算属性：过滤后的书籍列表
const filteredBooks = computed(() => {
  if (!searchText.value) {
    return books.value;
  }
  return books.value.filter(book => 
    book.title.toLowerCase().includes(searchText.value.toLowerCase()) ||
    (book.author && book.author.toLowerCase().includes(searchText.value.toLowerCase()))
  );
});

// 搜索功能
const onSearch = (value) => {
  searchText.value = value;
};

// 打开书籍
const openBook = (book) => {
  uni.navigateTo({
    url: `/pages/reader/reader?id=${book.id}&title=${encodeURIComponent(book.title)}`
  });
};

// 跳转到导入页面
const goToImport = () => {
  uni.switchTab({ url: '/pages/import/import' });
};

// 底部导航切换
const onTabChange = (index) => {
  current.value = index;
  if (index === 0) return; // 当前页
  if (index === 1) {
    uni.switchTab({ url: '/pages/import/import' });
  } else if (index === 2) {
    uni.switchTab({ url: '/pages/myInfo/myInfo' });
  }
};

// 页面加载时获取书籍列表
onMounted(() => {
  loadBooks();
});

// 加载书籍列表
const loadBooks = () => {
  try {
    const storedBooks = uni.getStorageSync('books') || [];
    books.value = storedBooks;
  } catch (e) {
    console.error('加载书籍失败:', e);
    books.value = [];
  }
};

// 监听页面显示事件，刷新书籍列表
uni.$on('booksUpdated', () => {
  loadBooks();
});
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  padding-bottom: 140rpx; // 给自定义tabbar预留空间
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-section {
  margin-bottom: 30rpx;
}

.bookshelf {
  .bookshelf-header {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
    
    .count {
      font-size: 28rpx;
      color: #999;
      margin-left: 10rpx;
    }
  }
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30rpx;
}

.book-item {
  background: white;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.15);
  }
  
  .book-cover {
    text-align: center;
    margin-bottom: 20rpx;
  }
  
  .book-info {
    text-align: center;
    
    .book-title {
      display: block;
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .book-author {
      display: block;
      font-size: 24rpx;
      color: #666;
      margin-bottom: 8rpx;
    }
    
    .book-progress {
      display: block;
      font-size: 22rpx;
      color: #999;
    }
  }
}

.empty-bookshelf {
  padding: 100rpx 0;
}
</style>